import os
import sys
from pathlib import Path
import logging
import io
from aip import AipSpeech
from pydub import AudioSegment
import sounddevice as sd
import numpy as np
import time
import datetime  # 添加datetime模块用于生成时间戳

# 设置项目根目录
current_file = Path(__file__).resolve()
project_root = current_file.parent.parent
if str(project_root) not in sys.path:
    sys.path.insert(0, str(project_root))

# 日志配置
log_dir = project_root
os.makedirs(log_dir, exist_ok=True)
log_file = os.path.join(log_dir, "app.log")
logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[logging.FileHandler(log_file), logging.StreamHandler()]
)

# 百度语音合成 API 配置
APP_ID = "118612326"
API_KEY = "8WOPLn1ZntLGU5395AcVVqaC"
SECRET_KEY = "lMXs1W84ai3l5JzyXSUnqFcdyicVE6JO"
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)

# 创建语音保存目录
voice_dir = "/home/elf/voice"
os.makedirs(voice_dir, exist_ok=True)

def tts_speak(text, lang="zh", spd=5, vol=5, per=0, silent=False):
    try:
        # 确保 PipeWire 环境变量设置正确
        if os.geteuid() == 0:
            user_id = os.environ.get("SUDO_UID", "1000")
            runtime_dir = f"/run/user/{user_id}"
            os.environ["XDG_RUNTIME_DIR"] = runtime_dir
            os.environ["PIPEWIRE_RUNTIME_DIR"] = runtime_dir
            if not silent:
                logging.info(f"设置 PipeWire 环境变量: XDG_RUNTIME_DIR={runtime_dir}")

        # 语音合成
        if not silent:
            logging.info(f"合成语音: {text}")
        result = client.synthesis(text, lang, 1, {"spd": spd, "vol": vol, "per": per})
        if isinstance(result, dict):
            if not silent:
                logging.error(f"语音合成失败: {result}")
            return

        # 处理音频数据
        audio = AudioSegment.from_mp3(io.BytesIO(result))
        sample_rate = 44100
        audio = audio.set_frame_rate(sample_rate)
        if audio.channels == 1:
            audio = audio.set_channels(2)
            
        wav_data = io.BytesIO()
        audio.export(wav_data, format="wav")
        wav_data.seek(0)

        # ============================================
        # 保存音频文件到指定目录（无任何终端显示）
        # ============================================
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = os.path.join(voice_dir, f"voice_{timestamp}.wav")
        with open(filename, "wb") as f:
            f.write(wav_data.getbuffer())
        wav_data.seek(0)  # 重置指针位置
        # ============================================

        # 使用 sounddevice 播放音频
        try:
            # 静默模式下不查询设备信息
            if not silent:
                devices = sd.query_devices()
                default_output = sd.default.device[1]
                device_info = devices[default_output]
                if device_info['name']=='default':
                    logging.info(f"使用音频设备: 耳机")
                else:
                    logging.info(f"使用音频设备: {device_info['name']}")

            # 转换音频数据
            audio_array = np.frombuffer(wav_data.read(), dtype=np.int16)
            
            # 静默播放
            with sd.OutputStream(samplerate=sample_rate) as stream:
                stream.write(audio_array)
            
            if not silent:
                logging.info(f"播报完成: {text}")

        except Exception:
            # 静默模式下不显示错误日志
            if not silent:
                pass
            
            # 备用方案: 保存为临时文件并使用pw-play
            temp_file = "/tmp/tts_temp.wav"
            audio.export(temp_file, format="wav")
            os.system(f"pw-play {temp_file} >/dev/null 2>&1")  # 重定向输出到null
            os.remove(temp_file)

    except Exception as e:
        if not silent:
            logging.error(f"TTS错误: {e}")

if __name__ == "__main__":
    # 静默模式测试
    tts_speak("测试静默播放模式", silent=True)
    
    # 正常模式测试
    tts_speak("测试正常播放模式")